package com.songcan.common.utils;

import com.songcan.common.vo.UserVO;

import java.util.Random;

public class HashPasswordService {

    private String hashAlgorithm= "SHA-256";

    private int hashIterations=5000;

    public HashPasswordService(String hashAlgorithm,int hashIterations){
        this.hashAlgorithm = hashAlgorithm;
        this.hashIterations = hashIterations;
    }



    // 生成密码和salt
    public void hashAuthentication(UserVO userVO){
        String salt = generateRandomPassword();
        SimpleHash simpleHash =new SimpleHash(SimpleHash.AlgorithmName.SHA256, userVO.getPassword(), salt, hashIterations);
        userVO.setSalt(salt);
        userVO.setPassword(simpleHash.toHex());
    }

    public void resetUserPassword(UserVO user){
        String salt = user.getSalt();
        SimpleHash simpleHash =new SimpleHash(SimpleHash.AlgorithmName.SHA256, user.getPassword(), salt, hashIterations);
        user.setPassword(simpleHash.toHex());
    }

    public String  generateRandomPassword(){
        byte[] saltByte = new byte[16];
        Random random = new Random();
        random.nextBytes(saltByte);
        return Hex.encodeToString(saltByte);
    }

    public String getHashAlgorithm() {
        return hashAlgorithm;
    }

    public void setHashAlgorithm(String hashAlgorithm) {
        this.hashAlgorithm = hashAlgorithm;
    }

    public int getHashIterations() {
        return hashIterations;
    }

    public void setHashIterations(int hashIterations) {
        this.hashIterations = hashIterations;
    }

    public Boolean matchPassword(String source, String salt, String target) {
        SimpleHash simpleHash =new SimpleHash(SimpleHash.AlgorithmName.SHA256, source, salt, hashIterations);
        return target.equals(simpleHash.toHex());
    }

}
